package com.example.bookmanagement.controller;

import com.example.bookmanagement.common.AjaxResponse;
import com.example.bookmanagement.dto.UserDTO;
import com.example.bookmanagement.service.UserService;
import com.example.bookmanagement.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public AjaxResponse login(@RequestBody UserDTO userDTO) {
        boolean authenticated = userService.authenticate(userDTO.getUsername(), userDTO.getPassword());
        log.info("User " + userDTO.getUsername() + " login, authenticated: " + authenticated);
        if (!authenticated) {
            return AjaxResponse.error("用户名或密码错误");
        }else{
            String token = JwtUtils.generateToken(userDTO.getUsername());
            log.info(" accessToken: " + token);
            Map<String, String> result = new HashMap<>();
            result.put("accessToken", token);
            return AjaxResponse.success(result);
        }

    }
}    